package com.epalmpay.controller.channel.iccard;


import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.epalmpay.util.RedisUtil;
import com.epalmpay.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.iccard.IcCardImportInDTO;
import com.epalmpay.dto.iccard.IcCardInDTO;
import com.epalmpay.dto.iccard.IcCardOutDTO;
import com.epalmpay.dto.iccard.IcCardShowListDTO;
import com.epalmpay.dto.system.PageDTO;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.Page;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.iccard.IIcCardService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.sms.ISMSService;
import com.epalmpay.service.weixin.IWxApiIcCardService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.Const;
import com.epalmpay.util.Tools;
import redis.clients.jedis.Jedis;

@Controller
@RequestMapping(value="/manager/iccard")
public class IcCardController extends BaseController{
	
	@Resource
	private IIcCardService icCardService;
	
	@Resource
	private IMemberService memberService;
	
	@Autowired
	protected ISMSService smsService;
	
	@Resource
	private IWxApiIcCardService wxApiIcCardService;
	
	/**
	 * 实体卡分页
	 * @param icCardInDTO
	 * @param pageDTO
	 * @return
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public IcCardShowListDTO SelectIcCardList(IcCardInDTO icCardInDTO,PageDTO pageDTO){
		IcCardShowListDTO icCardShowListDTO=new IcCardShowListDTO();
		
		try {
			Page page=Tools.pageEmtity(pageDTO);
			
			//查找到实体卡所有使用状态列表
			
			IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
			icCardOutDTO.setSuccessCount(icCardService.updateAutoDiscardIcCard(icCardInDTO));//查找到本渠道下的，挂失超过48小时的实体卡，进行废弃
			
			icCardShowListDTO=icCardService.selectIcCardList(icCardInDTO, page);
			icCardShowListDTO.setErrorCode(Rescode.SUCCESS,"处理成功");
			icCardShowListDTO.setPage(page);
			return icCardShowListDTO;
			
		} catch (ApplicationException ae) {
			// TODO Auto-generated catch block
			icCardShowListDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
		}
	    catch (Exception e){
		  icCardShowListDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
		  e.printStackTrace();
	  }
		return icCardShowListDTO;
	}
	
	
	/**
	 * 批量新增不记名未激活的实体卡
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/add")
	@ResponseBody
	public IcCardShowListDTO insertIcCardBatch(IcCardInDTO icCardInDTO){
		IcCardShowListDTO icCardShowListDTO = new IcCardShowListDTO();
		boolean result=false;
		result=icCardService.insertIcCardBatch(icCardInDTO);
		if(result){
			icCardShowListDTO.setErrorCode(Rescode.SUCCESS,"处理成功");
			return icCardShowListDTO;
		}else{
			icCardShowListDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			return icCardShowListDTO;
		}
	}
	
	@RequestMapping(value="/icCardImport")
	@ResponseBody
	public IcCardOutDTO finishBatchAddIcCard(@RequestBody IcCardImportInDTO icCardImportInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		icCardOutDTO=icCardService.insertIcCardImport(icCardImportInDTO);
		if(icCardOutDTO.getAllCount()==icCardOutDTO.getSuccessCount()){
			//全部导入成功
			icCardOutDTO.setErrorCode("1","预计导入"+icCardOutDTO.getAllCount()+"条，实际导入+"+icCardOutDTO.getSuccessCount()+"条，全部导入成功");
		}else{
			icCardOutDTO.setErrorCode("-1","未能全部导入：共需要导入"+icCardOutDTO.getAllCount()+"条，导入成功"
					+icCardOutDTO.getSuccessCount()+"条，卡号冲突导致导入失败"+icCardOutDTO.getErrorCount()+"条");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 实体卡后台发送验证码
	 * @param icCardInDTO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sendPhoneCode")
	@ResponseBody
	public IcCardOutDTO sendCode(IcCardInDTO icCardInDTO) throws Exception{
		//先根据电话号码查找是否存在存在电话号码是本号码的会员，
		//如果存在本会员，就发送验证码，如果不存在，就返回不存在本会员的信息反馈
		IcCardOutDTO icCardOutDTO=new IcCardOutDTO();
		Member member=new Member();
		Member memberIn=new Member();
		if(icCardInDTO.getPhone()!=null&&icCardInDTO.getPhone()!=""){
			String phone=icCardInDTO.getPhone();
			memberIn.setGroupId(icCardInDTO.getGroupId());
			memberIn.setPhone(icCardInDTO.getPhone());
			member=memberService.selectMemberByPhone(memberIn);
			if(member!=null){
				Long groupId=member.getGroupId();
				Long memberId=member.getId();
				icCardOutDTO.setMemberId(memberId);
				String type="2";
				logBefore(logger, "发送短信验证码");
				
				Map<String,String> map = new HashMap<String,String>();
				Date date=new Date();
				//短信验证码2分钟发送一次 验证码有效时间30分钟
				RedisUtil redisUtil = new RedisUtil();
				Jedis jedis = redisUtil.getJedis();
				/*Date verifyDate=(Date)Const.CacheMapObject.get(Const.SESSION_TiME_CODE+phone+type);
				if(verifyDate!=null){
					//当前时间120秒后
					Calendar calendar = Calendar.getInstance();  
					calendar.setTime(verifyDate);    
					calendar.add(Calendar.SECOND, 120);  
					if(calendar.getTime().after(date)){
						icCardOutDTO.setErrorCode("-1","2分钟内只能发送1条校验码。");
					}
				}*/
				Long verifyDate = jedis.ttl(Const.SESSION_PHONE_CODE+phone+type);
				if(verifyDate!=null){
					if(verifyDate >= 1680){//如果剩余生成时间大于1680秒，则抛出异常
						icCardOutDTO.setErrorCode("-1","2分钟内只能发送1条校验码。");
					}
				}
				try {
					String code="true".equals("false") ? "000000" : String.format("%.0f",(Math.random()*9+1)*100000);
		    		this.logger.info("---验证码---:"+code);
		    		Map<String, String> params=new HashMap<String, String>(); 
		    		boolean flag=smsService.sendRegionCode(groupId, code, BizEnum.SMSTemplateType.temp_SMS_104630027.getType(), phone, params);
		    		if(flag){
		    			//Const.CacheMapObject.put(Const.SESSION_PHONE_CODE+phone+type,code);
						//Const.CacheMapObject.put(Const.SESSION_TiME_CODE+phone+type, date);
						jedis.setex(Const.SESSION_PHONE_CODE+phone+type, 1800, code);
		    		}
					jedis.quit();
					icCardOutDTO.setErrorCode("1","验证码发送成功");
				} catch (Exception e) {
					e.printStackTrace();
					icCardOutDTO.setErrorCode("-2","验证码发送异常");
				}
				
				
			}else{
				icCardOutDTO.setErrorCode("-3","该手机号未注册会员，不可绑卡");
			}
		}else{
			icCardOutDTO.setErrorCode("-4","手机号不可为空");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 实体卡后台根据卡号获取初始密码
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/getInitPwd")
	@ResponseBody
	public IcCardOutDTO selectIcCardPwdByIcCardNo(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		if(icCardInDTO.getIccardNo()!=null&&icCardInDTO.getIccardNo()!=""){
			try {
				icCardOutDTO=icCardService.selectIcCardByIcCardNo(icCardInDTO);
				if(icCardOutDTO!=null){
					icCardOutDTO.setErrorCode("1","获取初始密码成功");
				}
			} catch (ApplicationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				icCardOutDTO.setErrorCode("-2","系统异常");
			}
		}else{
			icCardOutDTO.setErrorCode("-1","实体卡卡号不可为空");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 实体卡后台批量删除
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/batchDiscardIcCard")
	@ResponseBody
	public IcCardOutDTO updateBatchDiscardIcCard(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		if(icCardInDTO.getStr()!=null){
			try {
				String[] ids=icCardInDTO.getStr().split(",");
				
				for(int i=0;i<ids.length;i++){
					Long id=Long.parseLong(ids[i].toString());
					icCardInDTO.setId(id);
					icCardService.deleteIcCardById(icCardInDTO);
				}
				icCardOutDTO.setErrorCode("1","删除成功");
			} catch (ApplicationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				icCardOutDTO.setErrorCode("-2","删除失败");
			}
		}else{
			icCardOutDTO.setErrorCode("-1","实体卡ID不可为空");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 实体卡后台，异步校验验证码
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/checkCode")
	@ResponseBody
	public IcCardOutDTO selectCheckCode(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		
		if(icCardInDTO.getCode()!=null&&icCardInDTO.getPhone()!=null){
			
			String phone=icCardInDTO.getPhone();
			String code=icCardInDTO.getCode();
			String type="2";
			
			//String codemessage=(String)Const.CacheMapObject.get(Const.SESSION_PHONE_CODE+phone+type);
			RedisUtil redisUtil = new RedisUtil();
			Jedis jedis = redisUtil.getJedis();
			String codemessage = jedis.get(Const.SESSION_PHONE_CODE+phone+type);
			logBefore(logger, "原验证码"+codemessage);
			if(Tools.isEmpty(codemessage)||!codemessage.equals(code)){ 
				 //Response.getError("验证码输入错误");
				 icCardOutDTO.setErrorCode("-2","验证码输入错误");
			}else{
				icCardOutDTO.setErrorCode("1","验证码正确");
			}
			jedis.quit();
		}else{
			icCardOutDTO.setErrorCode("-1","手机号和验证码均不可为空");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 实体卡后台开卡(绑卡)
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/pinlessIcCard")
	@ResponseBody
	public IcCardOutDTO updatePinlessIcCard(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO=new IcCardOutDTO();
		if(icCardInDTO!=null){
			if(icCardInDTO.getIccardNo()!=null&&icCardInDTO.getIccardNo()!=""){
				try {
					icCardOutDTO=icCardService.selectIcCardByIcCardNo(icCardInDTO);
					if(icCardOutDTO.getMemberId()==null){
						//表明该实体卡未被使用过，可以进行绑卡；
						/*
						 * 利用手机号，对该手机号进行判断，判断该手机号是否是会员，
						 * 是会员就判断该会员在本渠道是否有正在使用的实体卡，
						 * 有就不能再绑定，如果有，但是已废弃，则可进行绑定，
						 * 如果有已挂失的实体卡，则对该已挂失的实体卡进行废弃再进行绑定
						 */
						if(icCardInDTO.getPhone()!=null){
							Member memberIn=new Member();
							memberIn.setPhone(icCardInDTO.getPhone());
							memberIn.setGroupId(icCardInDTO.getGroupId());
							
							Member member=memberService.selectMemberByPhone(memberIn);
							if(member.getId()!=null){
								
								//先校验验证码，验证码正确的再进行卡状态判断，避免先改变了卡状态，而验证码又不正确没进行绑卡
								/*
								 * 绑卡流程中，校验验证码，验证码校验通过，就进行绑卡
								 */
								String icCardNo=icCardInDTO.getIccardNo();
								String memberId=member.getId().toString();
								String phone=icCardInDTO.getPhone();
								String code=icCardInDTO.getCode();
								String type="2";
								//String codemessage=(String)Const.CacheMapObject.get(Const.SESSION_PHONE_CODE+phone+type);
								RedisUtil redisUtil = new RedisUtil();
								Jedis jedis = redisUtil.getJedis();
								String codemessage = jedis.get(Const.SESSION_PHONE_CODE+phone+type);
								logBefore(logger, "原验证码"+codemessage);
								if(Tools.isEmpty(codemessage)||!codemessage.equals(code)){ 
									 //Response.getError("验证码输入错误");
									 icCardOutDTO.setErrorCode("-6","验证码输入错误");
								}else{
									//验证码校验成功
									//判断会员在本渠道拥有的实体卡的状态
									IcCardOutDTO resultIcCardOutDTO=icCardService.selectIcCardByMemberIdAndStatus(member.getId(), icCardInDTO.getGroupId());
										
										if(resultIcCardOutDTO.getErrorCode().equals("-3")||resultIcCardOutDTO.getErrorCode().equals("-2")){
											//表示该会员在本渠道下有正处于挂失状态或者绑定状态的实体卡，绑卡操作会使得这张处于挂失状态的实体卡废弃
											IcCardInDTO updateIcCardInDTO=new IcCardInDTO();
											updateIcCardInDTO.setId(resultIcCardOutDTO.getId());
											updateIcCardInDTO.setStatus(3);
											updateIcCardInDTO.setSwitchStatus(0);
											icCardService.updateIcCardById(updateIcCardInDTO);//废弃该挂失状态的实体卡
										}
										
									try {
										icCardService.updatePinlessIcCard(icCardNo, memberId);
										icCardOutDTO.setErrorCode("1","绑定成功");
										jedis.del(Const.SESSION_PHONE_CODE+phone+type);
										jedis.quit();
									} catch (ApplicationException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
										icCardOutDTO.setErrorCode("-7","绑卡时系统异常");
									}
								}
								
							}else{
								logger.info(icCardInDTO.getPhone()+"该手机号并非是会员，不可进行绑卡");
								icCardOutDTO.setErrorCode("-5","+"+icCardInDTO.getPhone()+"+该手机号并非是会员，或并非是本渠道会员，不可进行绑卡");
							}
						
						}else{
							logger.info("手机号为空，不可进行绑卡操作");
							icCardOutDTO.setErrorCode("-4","手机号不可为空");
						}
					}else{
						logger.info("该实体卡已有会员使用，不可再次进行绑卡");
						icCardOutDTO.setErrorCode("-3","该实体卡已有会员使用，不可再次进行绑卡");
					}
				} catch (ApplicationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.info("验证实体卡是否可绑定时异常" + e);
				}
			}else{
				icCardOutDTO.setErrorCode("-2","实体卡号不可为空");
			}
		}else{
			icCardOutDTO.setErrorCode("-1","参数传入不完整");
		}
		return icCardOutDTO;
		
	}
	
	/**
	 * 实体卡后台修改启用禁用状态
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/changeSwitchStatus")
	@ResponseBody
	public IcCardOutDTO updateIcCardSwitchStatus(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		boolean result=false;
		result=icCardService.updateSwitchStatus(icCardInDTO);
		if(result){
			icCardOutDTO.setErrorCode("1","处理成功");
		}else{
			icCardOutDTO.setErrorCode("-1", "处理出现异常");
		}
		return icCardOutDTO;
	}
	
	/**
	 * 准备修改实体卡，
	 * 根据实体卡ID，去查找到对应的实体卡信息
	 * 为修改实体卡进行准备
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/toModification")
	@ResponseBody
	public IcCardOutDTO selectIcCardById(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO=icCardService.selectIcCardById(icCardInDTO);
		if(icCardOutDTO!=null){
			icCardOutDTO.setErrorCode(Rescode.SUCCESS,"处理成功");
			return icCardOutDTO;
		}else{
			icCardOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			return icCardOutDTO;
		}
	}
	
	/**
	 * 实体卡后台删除
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/toDiscardIcCard")
	@ResponseBody
	public IcCardOutDTO deleteIcCardById(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO=new IcCardOutDTO();
		try {
			if(icCardService.deleteIcCardById(icCardInDTO)){
				icCardOutDTO.setErrorCode(Rescode.SUCCESS,"删除成功");
			}else{
				icCardOutDTO.setErrorCode("-1","删除失败");
			}
			return icCardOutDTO;
		} catch (ApplicationException ae) {
			// TODO Auto-generated catch block
			logger.error(ae);
			icCardOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, ae.getMessage());
		} catch (Exception e) {
			icCardOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
		}
		return icCardOutDTO;
	}
	
	/**
	 * 去修改保存对实体卡的修改
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/toSaveChange")
	@ResponseBody
	public IcCardOutDTO updateIcCardById(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO = new IcCardOutDTO();
		try {
			if(icCardService.updateIcCardById(icCardInDTO)){
				icCardOutDTO.setErrorCode(Rescode.SUCCESS,"处理成功");
				return icCardOutDTO;
			}else{
				
			}
		} catch (ApplicationException ae) {
			// TODO Auto-generated catch block
			logger.error(ae);
			icCardOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, ae.getMessage());
		} catch (Exception e){
			icCardOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
		}
		return icCardOutDTO;
	}
	
	/**
	 * 后台实体卡挂失
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/lostIcCard")
	@ResponseBody
	public IcCardOutDTO updateLostIcCard(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO =new IcCardOutDTO();
		if(icCardInDTO!=null){
			String icCardNo=icCardInDTO.getIccardNo();
			String code=icCardInDTO.getCode();
			String phone=icCardInDTO.getPhone();
			String type="2";
			String status=icCardInDTO.getStatus().toString();
			if(status.equals("2")){
				try {
					//校验验证码
					RedisUtil redisUtil = new RedisUtil();
					Jedis jedis = redisUtil.getJedis();
					String codemessage = jedis.get(Const.SESSION_PHONE_CODE+phone+type);
					//String codemessage=(String)Const.CacheMapObject.get(Const.SESSION_PHONE_CODE+phone+type);
					logBefore(logger, "原验证码"+codemessage);
					if(Tools.isEmpty(codemessage)||!codemessage.equals(code)){ 
						icCardOutDTO.setErrorCode("-4","验证码输入错误");
					}else{
						wxApiIcCardService.updateIcCardStatus(icCardNo,"0", "4","0");
						icCardOutDTO.setErrorCode("1","挂失成功");
						jedis.del(Const.SESSION_PHONE_CODE+phone+type);
					}
					jedis.quit();
				} catch (ApplicationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					icCardOutDTO.setErrorCode("-3","实体卡挂失失败");
				}
			}else{
				icCardOutDTO.setErrorCode("-2","实体卡不处于已绑定状态，无法挂失");
			}
		}else{
			icCardOutDTO.setErrorCode("-1","传入参数不完整");
		}
		return icCardOutDTO;
		
	}
	
	/**
	 * 后台取消挂失
	 * @param icCardInDTO
	 * @return
	 */
	@RequestMapping(value="/cancelLostIcCard")
	@ResponseBody
	public IcCardOutDTO updateCancelLostIcCard(IcCardInDTO icCardInDTO){
		IcCardOutDTO icCardOutDTO =new IcCardOutDTO();
		try {
			String icCardNo=icCardInDTO.getIccardNo();
			//String icCardNo, String targetSwitchStatus, String targetStatus,String switchNo
			wxApiIcCardService.updateIcCardStatus(icCardNo,"1", "2","1");
			icCardOutDTO.setErrorCode("1","取消挂失成功");
		} catch (ApplicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			icCardOutDTO.setErrorCode("-1","取消挂失失败");
		}
		return icCardOutDTO;
	}
}
